<template>
	<view class="kebiao-page">
		<!-- 顶部学生和班级选择 -->
		<view class="select-header">
			<view class="left-dropdowns">
				<view class="select-item student-select" @click="showStudentPicker = true">
					<text>{{ currentStudent ? currentStudent.name : '' }}</text>
					<u-icon name="arrow-down" color="#333333" size="12"></u-icon>
				</view>
				<view class="select-item class-select" @click="showClassPicker = true">
					<text>{{ currentClass ? currentClass.name : '' }}</text>
					<u-icon name="arrow-down" color="#333333" size="12"></u-icon>
				</view>
			</view>
			<view class="avatar-wrapper">
				<image class="avatar" :src="parentAvatar" mode="aspectFill"></image>
			</view>
		</view>

		<!-- 主内容卡片：月份选择、课时信息、考勤标注信息、日历 -->
		<view class="main-content-card">
			<view class="summary-row">
				<view class="month-selection-group">
					<text class="month-label">月份选择</text>
					<view class="month-picker" @click="showMonthPicker = true">
						<text>{{ currentMonth }}</text>
						<u-icon name="arrow-down" color="#333333" size="12"></u-icon>
					</view>
				</view>
				<view class="course-hours-display">
					<text>{{ usedHours }}/{{ totalHours }}课时</text>
				</view>
				<view class="return-today" @click="returnToToday">
					<text>回到今天</text>
				</view>
			</view>

			<!-- 考勤标注信息 -->
			<view class="attendance-legend">
				<view class="legend-item">
					<view class="dot normal"></view>
					<text>正常</text>
				</view>
				<view class="legend-item">
					<view class="dot abnormal"></view>
					<text>缺勤</text>
				</view>
				<view class="legend-item">
					<view class="dot leave"></view>
					<text>请假</text>
				</view>
				<view class="legend-item">
					<view class="dot reschedule"></view>
					<text>调课</text>
				</view>
			</view>

			<!-- 日历区域 -->
			<view class="calendar-grid-section">
				<view class="week-header">
					<text v-for="(weekDay, index) in weekList" :key="index">{{ weekDay }}</text>
				</view>
				<view class="days-grid">
					<view class="day-item" v-for="(day, index) in calendarDays" :key="index"
						@click="selectDay(day)"
						:class="{ 
							'current-month-day': day.isCurrentMonth, 
							'today-day': day.isToday, 
							'other-month-day': day.isOtherMonth,
						}">
						<view class="date-wrapper" :class="{
							'attendance-normal': day.attendance === 'normal',
							'attendance-abnormal': day.attendance === 'abnormal',
							'attendance-leave': day.attendance === 'leave',
							'attendance-reschedule': day.attendance === 'reschedule'
						}">
							<text>{{ day.date }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 课时信息窗口 -->
			<view v-if="period.length > 0" class="period-section">
				<view class="period-header">{{ selectedDate }}</view>
				<view v-for="(item, idx) in period" :key="idx" :class="['period-row', 'period-attendance-' + mapAttendStatus(item.detailAttend)]">
					<text>第{{ idx + 1 }}节课</text>
				</view>
			</view>
		</view>

		<!-- 学生选择弹窗 -->
		<u-picker :show="showStudentPicker" :columns="[students.map(item => item.name)]" @confirm="selectStudent"
			@cancel="showStudentPicker = false" title="选择孩子"></u-picker>

		<!-- 班级选择弹窗 -->
		<u-picker :show="showClassPicker" :columns="[classes.map(item => item.name)]" @confirm="selectClass"
			@cancel="showClassPicker = false" title="选择班级"></u-picker>

		<!-- 月份选择弹窗 (u-datetime-picker) -->
		<u-datetime-picker :show="showMonthPicker" mode="year-month" :minDate="minDateTimestamp"
			:maxDate="maxDateTimestamp" :value="defaultMonthTimestamp" @confirm="onMonthConfirm"
			@cancel="showMonthPicker = false"></u-datetime-picker>

	</view>
</template>

<script>
	import { getParentUrl, getCourseStu, getCourseCla, getAttend, getAttendByDay } from '@/api/attend'

	export default {
		data() {
			return {
				showStudentPicker: false,
				showClassPicker: false,
				showMonthPicker: false,
				parentAvatar: '',
				usedHours: 9,
				totalHours: 20,
				students: [],
				classes: [],
				currentClass: null,
				parentId: '',
				campusId: '',
				currentYear: new Date().getFullYear(),
				currentMonth: new Date().getMonth() + 1,
				weekList: ['一', '二', '三', '四', '五', '六', '日'],
				attendanceData: {
					// 后端获取
				},
				period: [],
				selectedDate: '',
				currentStudent: null,
			}
		},
		computed: {
			studentActions() {
				return this.students.map(student => ({
					name: student.name,
					value: student.id
				}));
			},
			classActions() {
				return this.classes.map(_class => ({
					name: _class.name,
					value: _class.id
				}));
			},
			calendarDays() {
				const year = this.currentYear
				const month = this.currentMonth - 1 // `getMonth()` is 0-indexed, so adjust
				
				// 获取当月第一天和最后一天
				const firstDay = new Date(year, month, 1)
				const lastDay = new Date(year, month + 1, 0)
				
				// 获取当月第一天是星期几（0-6，0表示星期日）
				let firstDayOfWeek = firstDay.getDay()
				// 将星期日转换为7，使星期一作为一周的第一天
				firstDayOfWeek = firstDayOfWeek === 0 ? 7 : firstDayOfWeek
				
				// 计算需要显示的上个月的天数
				const prevMonthDays = firstDayOfWeek - 1
				
				// 生成日历数据
				const days = []
				
				// 添加上个月的日期
				const prevMonthLastDay = new Date(year, month, 0).getDate()
				for (let i = prevMonthDays; i > 0; i--) {
					const date = prevMonthLastDay - i + 1
					const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(date).padStart(2, '0')}`
					days.push({
						date,
						isCurrentMonth: false,
						isToday: false,
						isOtherMonth: true,
						attendance: this.attendanceData[dateStr],
						fullDate: dateStr
					})
				}
				
				// 添加当月的日期
				const today = new Date().getDate()
				const todayMonth = new Date().getMonth()
				const todayYear = new Date().getFullYear()

				for (let i = 1; i <= lastDay.getDate(); i++) {
					const dateStr = `${year}-${String(month + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`
					days.push({
						date: i,
						isCurrentMonth: true,
						isToday: i === today && year === todayYear && month === todayMonth,
						isOtherMonth: false,
						attendance: this.attendanceData[dateStr],
						fullDate: dateStr
					})
				}
				
				// 添加下个月的日期，确保总共有42个日期（6行）
				const remainingDays = 42 - days.length
				for (let i = 1; i <= remainingDays; i++) {
					const dateStr = `${year}-${String(month + 2).padStart(2, '0')}-${String(i).padStart(2, '0')}`
					days.push({
						date: i,
						isCurrentMonth: false,
						isToday: false,
						isOtherMonth: true,
						attendance: this.attendanceData[dateStr],
						fullDate: dateStr
					})
				}
				
				return days
			},
			minDateTimestamp() {
				return new Date('2020-01-01').getTime();
			},
			maxDateTimestamp() {
				return new Date().getTime();
			},
			defaultMonthTimestamp() {
				return new Date(this.currentYear, this.currentMonth - 1, 1).getTime();
			}
		},
		methods: {
			async fetchParentInfo() {
				// 1. 获取家长头像
				const parentRes = await getParentUrl(this.parentId, this.campusId)
				this.parentAvatar = parentRes.data.parentUrl

				// 2. 获取家长孩子
				const stuRes = await getCourseStu(this.parentId, this.campusId)
				this.students = (stuRes.data.list || []).map(stu => ({
					name: stu.stuName,
					id: stu.stuId,
					...stu
				}))

				// 3. 获取第一个孩子的班级
				if (this.students.length > 0) {
					this.currentStudent = this.students[0];
					this.fetchClassInfo(this.students[0].id)
				}
			},
			async fetchClassInfo(stuId) {
				const claRes = await getCourseCla(stuId)
				this.classes = (claRes.data.list || []).map(cla => ({
					name: cla.claDescribe || `班级${cla.claId}`,
					id: cla.claId,
					...cla
				}))
				// 默认选第一个班级，设置课时和当前班级
				if (this.classes.length > 0) {
					this.currentClass = this.classes[0]
					this.usedHours = this.currentClass.passNum || 0
					this.totalHours = this.currentClass.totalNum || 0
					// 获取考勤数据
					await this.fetchAttendanceData(
						this.currentStudent ? this.currentStudent.id : this.students[0].id,
						this.currentClass.id,
						this.currentYear,
						this.currentMonth
					)
					this.period = [];
					this.selectedDate = '';
				} else {
					this.currentClass = null
					this.usedHours = 0
					this.totalHours = 0
					this.attendanceData = {}
					this.period = [];
					this.selectedDate = '';
				}
			},
			async fetchAttendanceData(stuId, claId, year, month) {
				const monthStr = `${year}-${String(month).padStart(2, '0')}`
				const res = await getAttend(stuId, claId, monthStr)
				const list = (res.data.list || [])
				const attendanceData = {}
				list.forEach(item => {
					attendanceData[item.detailCreTime] = this.mapAttendStatus(item.detailAttend)
				})
				this.attendanceData = attendanceData
			},
			mapAttendStatus(code) {
				switch (code) {
					case '0': return 'normal'
					case '1': return 'abnormal'
					case '2': return 'leave'
					case '3': return 'reschedule'
					default: return ''
				}
			},
			selectStudent(e) {
				const selectedName = e.value[0]
				const selectedStudent = this.students.find(student => student.name === selectedName)
				if (selectedStudent) {
					this.currentStudent = selectedStudent;
					this.fetchClassInfo(selectedStudent.id)
					this.period = [];
					this.selectedDate = '';
				}
				this.showStudentPicker = false
			},
			selectClass(e) {
				const selectedName = e.value[0];
				const selectedClass = this.classes.find(_class => _class.name === selectedName);
				if (selectedClass) {
					this.currentClass = selectedClass;
					// 切换班级时，更新课时
					this.usedHours = selectedClass.passNum || 0
					this.totalHours = selectedClass.totalNum || 0
					// 获取考勤数据
					this.fetchAttendanceData(
						this.currentStudent ? this.currentStudent.id : this.students[0].id,
						selectedClass.id,
						this.currentYear,
						this.currentMonth
					)
					this.period = [];
					this.selectedDate = '';
				}
				this.showClassPicker = false;
			},
			onMonthConfirm(e) {
				const selectedDate = new Date(e.value);
				this.currentYear = selectedDate.getFullYear();
				this.currentMonth = selectedDate.getMonth() + 1;
				this.showMonthPicker = false;
				// 获取考勤数据
				if (this.students.length > 0 && this.currentClass) {
					this.fetchAttendanceData(
						this.currentStudent ? this.currentStudent.id : this.students[0].id,
						this.currentClass.id,
						this.currentYear,
						this.currentMonth
					)
					this.period = [];
					this.selectedDate = '';
				}
			},
			returnToToday() {
				const today = new Date();
				this.currentYear = today.getFullYear();
				this.currentMonth = today.getMonth() + 1;
				// 获取考勤数据
				if (this.students.length > 0 && this.currentClass) {
					this.fetchAttendanceData(
						this.currentStudent ? this.currentStudent.id : this.students[0].id,
						this.currentClass.id,
						this.currentYear,
						this.currentMonth
					)
					this.period = [];
					this.selectedDate = '';
				}
			},
			changeMonth(delta) {
				let newMonth = this.currentMonth + delta;
				let newYear = this.currentYear;

				if (newMonth > 12) {
					newMonth = 1;
					newYear++;
				} else if (newMonth < 1) {
					newMonth = 12;
					newYear--;
				}

				const newDate = new Date(newYear, newMonth - 1, 1);
				const maxAllowedDate = new Date(this.maxDateTimestamp);

				// Only allow navigating to past or current month
				if (newDate.getTime() <= maxAllowedDate.getTime()) {
					this.currentMonth = newMonth;
					this.currentYear = newYear;
					this.period = [];
					this.selectedDate = '';
				} else {
					uni.$u.toast('不能选择未来的月份'); // uView toast
				}
			},
			onCalendarChange(e) {
				// This method is now empty as the selectedDate logic has been removed
			},
			async selectDay(day) {
				if (day.isCurrentMonth && day.fullDate) {
					this.selectedDate = day.fullDate;
					await this.fetchPeriodByDay(day.fullDate);
				}
			},
			async fetchPeriodByDay(day) {
				if (!this.students.length || !this.currentClass) {
					this.period = [];
					return;
				}
				const stuId = this.currentStudent ? this.currentStudent.id : this.students[0].id;
				const claId = this.currentClass.id;
				const res = await getAttendByDay(stuId, claId, day);
				const list = (res.data.list || []);
				this.period = list;
			},
		},
		onLoad() {
			// 获取本地存储的 parentId 和 campusId
			this.parentId = uni.getStorageSync('parentId')
			this.campusId = uni.getStorageSync('campusId')
			this.fetchParentInfo()
		}
	}
</script>

<style lang="scss" scoped>
	.kebiao-page {
		background-color: #2c57f6;
		min-height: 100vh;
		padding-bottom: 20rpx;
	}

	.select-header {
		padding: 100rpx 50rpx 15rpx;
		display: flex;
		align-items: flex-start;
		justify-content: space-between;
		position: relative;
	}

	.left-dropdowns {
		display: flex;
		flex-direction: column;
		margin-right: 20rpx;
	}

	.select-item {
		min-width: 210rpx;
		min-height: 40rpx;
		background-color: #ffffff;
		border-radius: 10rpx;
		padding: 10rpx 20rpx;
		color: #333333;
		font-size: 30rpx;
		display: flex;
		align-items: center;
		margin-bottom: 40rpx;
		justify-content: space-between;

		text {
			margin-right: 10rpx;
		}
	}

	.avatar-wrapper {
		position: relative;
		align-self: flex-start;
		display: flex;
		margin-right: 80rpx;
		.avatar {
			width: 164rpx;
			height: 164rpx;
			border-radius: 50%;
		}
	}

	.main-content-card {
		background-color: #ffffff;
		margin: 0;
		border-radius: 20rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}

	.summary-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.month-selection-group {
		display: flex;
		align-items: center;

		.month-label {
			font-size: 30rpx;
			margin-right: 15rpx;
		}

		.month-picker {
			display: flex;
			align-items: center;
			background-color: #ffffff;
			border-radius: 10rpx;
			padding: 8rpx 15rpx;
			font-size: 30rpx;
			min-width: 100rpx;
			border: 1px solid #bcbcbc;
			justify-content: space-between;

			text {
				margin-right: 10rpx;
			}

			u-icon {
				margin-left: auto;
			}
		}
	}

	.course-hours-display {
		font-size: 30rpx;
		flex-grow: 1;
		text-align: center;
	}

	.return-today {
		font-size: 28rpx;
		color: #565656;
	}

	.attendance-legend {
		background-color: #efefef;
		color: #000000;
		margin-bottom: 30rpx;
		padding: 20rpx;
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		gap: 48rpx;
	}

	.legend-item {
		display: flex;
		align-items: center;
		margin-bottom: 0;
		gap: 12rpx;
	}

	.dot {
		width: 20rpx;
		height: 20rpx;
		border-radius: 50%;
		margin-right: 5rpx;
	}

	.normal {
		background-color: #4caf50;
	}

	.abnormal {
		background-color: #ff0000;
	}

	.leave {
		background-color: #2196f3;
	}

	.reschedule {
		background-color: #ff9800;
	}

	text {
		font-size: 28rpx;
	}

	.calendar-grid-section {
		background-color: #ffffff;
		border-radius: 10rpx;
		padding: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
		margin-top: 20rpx;

		.week-header {
			display: flex;
			justify-content: space-around;
			margin-bottom: 20rpx;
			font-size: 28rpx;
			color: #999999;

			text {
				flex: 1;
				text-align: center;
			}
		}

		.days-grid {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			.day-item {
				width: calc(100% / 7);
				text-align: center;
				padding: 10rpx 0;
				position: relative;
				font-size: 32rpx;
				color: #333333;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				min-height: 50rpx;

				&.current-month-day {
					color: #333333;
				}

				&.today-day {
					color: #4a90e2;
					font-weight: bold;
				}

				&.other-month-day {
					color: #aaaaaa;
				}

				.date-wrapper {
					display: flex;
					align-items: center;
					justify-content: center;
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;

					&.attendance-normal {
						background-color: #4caf50;
						color: #ffffff;
						font-weight: bold;
						text {
							color: #ffffff;
						}
					}

					&.attendance-abnormal {
						background-color: #ff0000;
						color: #ffffff;
						font-weight: bold;
						text {
							color: #ffffff;
						}
					}

					&.attendance-leave {
						background-color: #2196f3;
						color: #ffffff;
						font-weight: bold;
						text {
							color: #ffffff;
						}
					}

					&.attendance-reschedule {
						background-color: #ff9800;
						color: #ffffff;
						font-weight: bold;
						text {
							color: #ffffff;
						}
					}
				}
			}
		}
	}

	.period-section {
		margin-top: 30rpx;
		background: #fff;
		border-radius: 0;
		border: 1px solid #e0e0e0;
		box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.08);
		padding: 0 0 10rpx 0;
		overflow: hidden;
	}

	.period-header {
		text-align: center;
		font-size: 30rpx;
		font-weight: bold;
		padding: 20rpx 0 18rpx 0;
		letter-spacing: 2rpx;
		color: #333;
		background: #f7f7f7;
	}

	.period-row {
		margin: 0 30rpx 16rpx 30rpx;
		padding: 18rpx 0;
		border-radius: 12rpx;
		text-align: center;
		font-size: 32rpx;
		font-weight: bold;
		color: #fff;
	}

	.period-attendance-normal {
		background-color: #4caf50;
	}

	.period-attendance-abnormal {
		background-color: #ff0000;
	}

	.period-attendance-leave {
		background-color: #2196f3;
	}

	.period-attendance-reschedule {
		background-color: #ff9800;
	}
</style>